package com.quicks.beauty.server.web;

import com.quicks.beauty.core.entity.UserAddress;
import com.quicks.beauty.core.entity.WxUser;
import com.quicks.beauty.core.vo.InviteUserDetailVO;
import com.quicks.beauty.core.vo.InviteUserVO;
import com.quicks.beauty.core.vo.UserPointsDetailVO;
import com.quicks.beauty.server.common.AjaxResult;
import com.quicks.beauty.server.service.UserService;
import com.quicks.beauty.server.vos.WxUserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import weixin.popular.util.EmojiUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "user")
@Api(tags = "获取用户的信息")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * TODO 首次注册
     *
     * @param openId
     * @param nickName
     * @param avatar
     * @return
     */
    @RequestMapping(value = "registry", method = RequestMethod.POST)
    @ApiOperation(value = "首次注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "用户OpenID，", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "nickName", value = "昵称，", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "avatar", value = "头像，", paramType = "query", required = true, dataType = "Integer")
    })
    public AjaxResult initUser(@RequestParam(value = "openId") String openId,
                               @RequestParam(value = "nickName") String nickName,
                               @RequestParam(value = "avatar") String avatar,
                               String fromUser) {
        AjaxResult result = new AjaxResult();
        String emojis = EmojiUtil.removeAllEmojis(nickName);
        nickName = emojis;
        try {
            WxUser wxUser = userService.selectByOpenId(openId);
            if (wxUser != null) {
                String nickName1 = wxUser.getNickName();
                String avatar1 = wxUser.getAvatar();
                if(nickName1!=nickName && avatar1!=avatar){
                    wxUser.setNickName(nickName).setAvatar(avatar);
                    int i = userService.updateWxUser(wxUser);
                    result.setSuccess(true);
                    result.setData(wxUser.getId());
                } else {
                    result.setSuccess(false);
                    result.setData(wxUser.getId());
                    result.setMsg("该用户已注册");
                }
            } else {
                WxUser newUser = userService.addWxUser(openId, nickName, avatar,fromUser);
                result.setSuccess(true);
                result.setData(newUser.getId());
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("系统打盹,请稍后...");
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 我的积分详情
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "我的积分详情")
    @RequestMapping(value = "pointList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID，", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页面，", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "数量，", paramType = "query", required = true, dataType = "Integer")
    })
    public AjaxResult getUserPointsList(@RequestParam("userId") String userId,
                                        @RequestParam("pageNum") Integer pageNum,
                                        @RequestParam("pageSize") Integer pageSize) {
        AjaxResult result = new AjaxResult();
        try {
            List<UserPointsDetailVO> list = userService.getUserPointsList(userId, pageNum, pageSize);
            list.forEach(st -> {
                int kinds = st.getKinds();
                if (kinds == 0) {
                    st.setRemark("消费");
                } else if (kinds == 1) {
                    st.setRemark("新用户注册赠送");
                } else if (kinds == 2) {
                    st.setRemark("消费凭证兑换");
                } else if (kinds == 3) {
                    st.setRemark("邀请好友赠送");
                }else if (kinds == 4) {
                    st.setRemark("订单取消");}
            });
            result.setSuccess(true);
            result.setData(list);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("系统错误!");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 我的总积分
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "我的总积分")
    @RequestMapping(value = "point", method = RequestMethod.GET)

//    @ApiImplicitParam(name = "userId", value = "用户的Id", dataType = "String", required = true)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID，", paramType = "query", required = true, dataType = "String")
    })
    public AjaxResult getUserPoint(@ApiParam(value = "userId") @RequestParam("userId") String userId) {
        AjaxResult result = new AjaxResult();
        try {
            int list = userService.getUserTotalPoint(userId);
            result.setSuccess(true);
            result.setData(list);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("系统错误!");
            e.printStackTrace();
        }
        return result;
    }


    @ApiOperation(value = "登录")
    @RequestMapping(value = "login", method = RequestMethod.GET)
    @ApiImplicitParam(name = "openId", value = "用户OpenID，", paramType = "query", required = true, dataType = "String")
    public AjaxResult loginUserByOpenId(@ApiParam(value = "openId") @RequestParam("openId") String openId) {
        AjaxResult result = new AjaxResult();
        try {
            WxUserVO user = userService.getMySelfByOpenId(openId);
            result.setSuccess(true);
            result.setData(user);
            result.setMsg("ok");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("服务器打盹中....");
            e.printStackTrace();
        }
        return result;
    }

    @ApiOperation(value = "地址列表")
    @RequestMapping(value = "addressList", method = RequestMethod.GET)
    @ApiImplicitParam(name = "userId", value = "用户ID，", paramType = "query", required = true, dataType = "String")
    public AjaxResult getUserAddressList(String userId){
        AjaxResult result = new AjaxResult();
        try {
            List<UserAddress> list = userService.getUserAddressList(userId);
            if (!list.isEmpty()) {
                result.setSuccess(true);
                result.setData(list);
            }else {
                result.setSuccess(false);
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("服务器打盹中....");
            e.printStackTrace();
        }
        return result;
    }

    @ApiOperation(value = "添加用户地址")
    @RequestMapping(value = "insertAddress", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "province", value = "省", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "city", value = "市区", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "town", value = "县", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "others", value = "详细信息", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "mobile", value = "手机号", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", required = true, dataType = "String")
    })
    public AjaxResult addUserAddress(String userId,String province,String city,String town,String others,String mobile,String username){
        AjaxResult result = new AjaxResult();
        try {
            UserAddress address = userService.addUserAddress(userId, province, city, town, others, mobile, username);
            result.setSuccess(true);
            result.setData(address.getId());
            result.setMsg("ok");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("服务器打盹中....");
            e.printStackTrace();
        }
        return result;
    }


    // getUserInvited

    @ApiOperation(value = "邀请人")
    @RequestMapping(value = "myInvited", method = RequestMethod.GET)
    @ApiImplicitParam(name = "useId", value = "用户userId，", paramType = "query", required = true, dataType = "String")
    public AjaxResult getInvitedUsers(@ApiParam(value = "userId") @RequestParam("userId") String userId) {
        AjaxResult result = new AjaxResult();
        try {
             List<InviteUserVO> user = userService.getUserInvited(userId);
            result.setSuccess(true);
            result.setData(user);
            result.setMsg("ok");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("服务器打盹中....");
            e.printStackTrace();
        }
        return result;
    }
    @RequestMapping(value = "myInvitedDetail",method = RequestMethod.GET)
    public AjaxResult myInvitedDetail(String userId){
        AjaxResult result = new AjaxResult();
        try {
            List<InviteUserVO> user = userService.getUserInvited(userId);
            List<InviteUserDetailVO> userDetail = new ArrayList<InviteUserDetailVO>();
            if(user.size()>0){
                int i =0;
                int j =0;
                for(InviteUserVO invitedUser: user){
                    InviteUserDetailVO inviteUserDetail = new InviteUserDetailVO();
                    inviteUserDetail.setInvitedPoint(invitedUser.getPoints());
                    inviteUserDetail.setInvitedAvatar(invitedUser.getInvitedAvatar());
                    inviteUserDetail.setInvitedNickName(invitedUser.getInvitedNickName());
                    inviteUserDetail.setInvitedTime(invitedUser.getInvitedTime());
                    inviteUserDetail.setInvitedUserId(invitedUser.getInvitedUserId());
                    inviteUserDetail.setUserId(invitedUser.getUserId());
                    //inviteUserDetail.setBillPoint(-1);
                   int count =  userService.findOrderNum(invitedUser.getInvitedUserId());
                   if(count >0){
                       Map<String,Object> map = userService.getBillAmount(invitedUser.getInvitedUserId());
                       InviteUserDetailVO inviteUserDetail1 = new InviteUserDetailVO();
                       inviteUserDetail1.setInvitedPoint((int)map.get("points")/2);
                       inviteUserDetail1.setInvitedAvatar(invitedUser.getInvitedAvatar());
                       inviteUserDetail1.setInvitedNickName(invitedUser.getInvitedNickName());
                       inviteUserDetail1.setInvitedTime((String)map.get("createTime"));
                       inviteUserDetail1.setInvitedUserId(invitedUser.getInvitedUserId());
                       inviteUserDetail1.setUserId(invitedUser.getUserId());
                        j++;
                       userDetail.add(inviteUserDetail1);

                   }
                    i++;
                    userDetail.add(inviteUserDetail);

                }
                InviteUserDetailVO inv = new InviteUserDetailVO();
                inv.setFriend(i);
                inv.setBillFriend(j);
                userDetail.add(inv);

            }

            result.setSuccess(true);
            result.setData(userDetail);
            result.setMsg("ok");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("服务器打盹中....");
            e.printStackTrace();
        }
        return result;
    }

}
